using _ReplaceString_.UI.Styles;
using Hjson;
using RSCore;
using Terraria.GameContent.UI.Elements;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.Core;
using Terraria.ModLoader.UI;

namespace _ReplaceString_.UI.Elements;

public class RightPanel : UIBase
{
	private ModInfo _mod;

	public RightPanel(ModInfo mod, Vector2 size, LeftPanel leftPanel)
	{
		_mod = mod;
		BackgroundColor = UICommon.DefaultUIBlue;
		Width.Pixels = size.X;
		Height.Pixels = size.Y;
		AddStyle(UIType.Panel, UIBackground.Rect, UILayout.Vertical);

		const int TitleHeight = 40;
		const int ButtonHeight = 60;
		const int MarginV = 6;

		var title = new TextWrap($"{mod.Name}")
		{
			PaddingBottom = 6,
		};
		title.AddStyle(UISize.Fill,
			UISize.TransformMargin(MarginV, Direction.LeftRight),
			UISize.FixedHeight(TitleHeight),
			UIRender.Edge(Direction.Down));
		Append(title);


		var container = new PackageGroup(mod.Name, leftPanel);
		container.AddStyle(UISize.Fill, UISize.FlexibleHeight);
		Append(container);

		var buttons = new UIBase()
		{
			PaddingTop = 12,
		};
		buttons.AddStyle(UILayout.Horizontal,
			UISize.Fill, UISize.FixedHeight(ButtonHeight),
			UISize.TransformMargin(MarginV, Direction.LeftRight),
			UIRender.Edge(Direction.Up));
		Append(buttons);

		UIStyle[] buttonStyle = [UISize.Fill, UISize.FlexibleWidth, UIBackground.Rect, UIRender.Click];
		var openFolder = new TextWrap(ModHelper.GetText("Config.OpenFolder"))
		{
			MarginLeft = 6,
			MarginRight = 6,
			BackgroundColor = UICommon.DefaultUIBlueMouseOver,
		};
		openFolder.AddStyle(buttonStyle);
		openFolder.OnLeftClick += OpenFolder;
		buttons.Append(openFolder);

		var export = new TextWrap(new UIText(ModHelper.GetText("Config.Export")))
		{
			MarginLeft = 6,
			MarginRight = 6,
			BackgroundColor = UICommon.DefaultUIBlueMouseOver,
		};
		export.AddStyle(buttonStyle);
		export.OnLeftClick += Export;
		buttons.Append(export);
	}

	private void Export(UIMouseEvent evt, UIElement listeningElement)
	{
		var folder = Directory.CreateDirectory($"{ModHelper.ExportPath}/{_mod.Name}");
		folder = folder.CreateSubdirectory(_mod.Version.ToString());
		TmodFile modFile;
		if (ModLoader.TryGetMod(_mod.Name, out var mod))
		{
			modFile = mod.File;
			var package = TextLoader.Export(mod,
				GameCulture.FromCultureName(GameCulture.CultureName.English),
				GameCulture.FromCultureName(GameCulture.CultureName.Chinese));

			foreach (var content in package.Directories)
			{
				TextIO.SaveHjson($"{folder.FullName}/{content.Name}.hjson", package, _mod.Name);
			}
			TextIO.WritePackage($"{folder.FullName}/Demo", package);
			package = TextIO.ReadPackage($"{folder.FullName}/Demo");
		}
		else
		{
			var package = TextLoader.ExportHjson(_mod.Name, out modFile);

			foreach (var content in package.Directories)
			{
				TextIO.SaveHjson($"{folder.FullName}/{content.Name}.hjson", content, _mod.Name);
			}

			using var stream = File.CreateText($"{folder.FullName}/Test.hjson");
			TextIO.WritePackage($"{folder.FullName}/Demo", package);
			package = TextIO.ReadPackage($"{folder.FullName}/Demo");
		}

		using (modFile.Open())
		{
			File.WriteAllBytes($"{folder.FullName}/{_mod.Name}.dll", modFile.GetModAssembly());

			var localization = folder.CreateSubdirectory("Localization");
			foreach (var entry in modFile.Where(e => e.Name.EndsWith(".hjson", StringComparison.Ordinal)))
			{
				var name = entry.Name;
				var dir = Path.GetDirectoryName(name.StartsWith("Localization") ? name[("Localization".Length + 1)..] : name);
				if (!string.IsNullOrEmpty(dir) && dir != "Localization")
				{
					localization.CreateSubdirectory(dir);
				}
				using var reader = new StreamReader(modFile.GetStream(entry));
				File.WriteAllText($"{localization.FullName}/{Path.GetFileName(name)}", reader.ReadToEnd());
			}
		}
		Task.Run(() => Utils.OpenFolder(folder.FullName));
	}

	private void OpenFolder(UIMouseEvent evt, UIElement listeningElement)
	{
		var folder = Directory.CreateDirectory($"{ModHelper.PackagePath}/{_mod.Name}");
		Task.Run(() => Utils.OpenFolder(folder.FullName));
	}
}